package com.yq.activemq.helloworld;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

public class Sender {

    /**
     * 消息服务器地址
     */
    public static final String BROKER_URL = "tcp://localhost:61616";

    public static void main(String[] args) {
        Sender sender = new Sender();
        for (int i = 0; i < 10; i++) {
            sender.sendMessage("Hello ActiveMQ " + i);
        }
    }

    private void sendMessage(String msg) {
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(BROKER_URL);
        Connection connection = null;
        Session session = null;
        MessageProducer producer = null;
        try {
            connection = connectionFactory.createConnection();
            session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
            TextMessage message = session.createTextMessage(msg);
            Queue destination = session.createQueue("myQueue");
            producer = session.createProducer(destination);
            producer.send(message);
        } catch (JMSException e) {
            e.printStackTrace();
        } finally {
            try {
                if (producer != null) {
                    producer.close();
                }
                if (session != null) {
                    session.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }
    }
}
